<script setup>
import {ref} from "vue"
import {goNeighborhood,getRouteParams} from "../../tools/go";
import {fileCount, zipFile} from "../../tools/checkFileHash.ts";
import {getUserId, set} from "../../store";
import {
  addPost, deleteEditPost, delPostImg,
  getUploadVideoStatus,
  getUserPost,
  modifyPost, savePost, stopUploadVideo, uploadPostImg,
  uploadPostVideo
} from "../../api/neighborhood/neighborhood";
import {baseUrl} from "../../api/http";
import Dialogue from "../../components/popup/dialogue.vue";
import {bMessage} from "../../components/popup/popup";
import {get} from "../../store";
import UniIcons from "../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";

const form = ref({
  id: 0,
  content: "",
  type: "分享生活",
  status: 2,
  address: null,
  latitude: 0,
  updateBy: getUserId()
})

const file = ref([])

//操作文件
const subFile = ref()
const subFileHash = ref()

const prop = ref(0)

//上传图片
const updateImg = () => {

  let input = document.createElement("input");
  input.type = "file";
  input.accept = "image/*";
  input.onchange = async function (e) {
    let a = e.target.files;

    for (let i = 0; i < a.length; i++) {
      await zipFile(a[i]).then(res => {
        let formData = new FormData();

        formData.append("img", res)
        formData.append("user", form.value.updateBy)
        formData.append("postId", form.value.id)

        uploadPostImg(formData).then(resa => {
          file.value.push({
            id: 0,
            clientUrl: resa.data,
            type: 'png'
          })
          // init()
        })

      })
    }




  }
  input.click()


}

//上传视频
const fn = () =>{
  const input = document.createElement('input')
  input.type='file'
  input.accept='video/*'
  input.onchange = (e) =>{
    let a = e.target.files[0]
    bMessage('视频开始压缩','success')
    fileCount(a).then(res =>{
      const fileChunk = res
      let index = 0
      bMessage('视频开始上传','success')
      const Task = () =>{
        const formData = new FormData()
        getUploadVideoStatus(fileChunk[0].hashName,form.value.updateBy,form.value.id).then(res =>{
          if(res.data === null){
            bMessage('视频上传失败','success')
            return;
          }
          if(index !== res.data.currentChunk){
            index = res.data.currentChunk
          }else {
            index = res.data.nextChunk
          }
          if(res.data.currentChunk === null){
            index = 0
          }
          prop.value = Math.ceil(index / fileChunk.length * 100)
          subFileHash.value = fileChunk[0].hashName
          if(index >= fileChunk.length){
            formData.append('video',fileChunk[0].chunk)
            formData.append('Hash',fileChunk[0].hashName)
            formData.append('chunkHash','end')
            formData.append('user',form.value.updateBy)
            formData.append('postId',form.value.id)
            formData.append('originFileName',a.name)
            formData.append('index',index)
            uploadPostVideo(formData).then(res =>{
              prop.value = 0
              bMessage('视频上传成功','success')
              file.value.push({
                id:0,
                clientUrl:res.data,
                type:'m4v'
              })
              console.log(file.value)
            })
            return;
          }
          formData.append('video',fileChunk[index].chunk)
          formData.append('Hash',fileChunk[index].hashName)
          formData.append('chunkHash',fileChunk[index].chunkHash)
          formData.append('user',form.value.updateBy)
          formData.append('postId',form.value.id)
          formData.append('originFileName',a.name)
          formData.append('index',index)
          uploadPostVideo(formData).then(res =>{
            if(res.code === 200){
              timeUp = setTimeout(Task,1000)
            }
          })
        })
      }
      Task()
    })
  }
  input.click()
}


//预览图片
const previewImage = (url) => {
  uni.previewImage({
    current: 0,
    urls: [url],
  });
};

//发布
const submit = () => {
  form.value.status = 1
  form.value.type = "分享生活"
  modifyPost(form.value).then(res => {
    if (res.code === 200) {
      goNeighborhood()
    }
  })
}

//保存并退出
const save = () => {
  savePost(form.value).then(res => {
    if (res.code === 200) {
      goNeighborhood()
    }
  })
}

const noSave = () => {
  deleteEditPost(form.value.id, form.value.updateBy)
      .then(res => {
        // console.log(res)
        if (res.code === 200) {
          goNeighborhood()
        }
      })
}

const exit = () => {
  if (form.value.content === ""
      || form.value.content === null && file.value.length === 0
      || getRouteParams("id") !== null) {
    goNeighborhood()
  } else {
    diaStatus.value = true
  }
}

const diaStatus = ref(false)
const diaStatusDel = ref(false)
const diaStatusStop = ref(false)
let timeUp = null;


//获取未发布的内容
const getNoPublic = () => {
  getUserPost({
    page: 1,
    size: 1,
    updateBy: getUserId()
  }).then(res => {
    if (getRouteParams("id") !== null) {
      let post = get()["post"];
      console.log(post)
      form.value.content = post.content
      form.value.type = post.type
      form.value.id = post.id
      file.value = post.file

      return;
    }

    if (res.data.records.length !== 0) {
      let a = res.data.records[0]
      form.value.content = a.content
      form.value.type = a.type
      form.value.id = a.id
      file.value = a.file

      return
    }
    addPost({
      updateBy: getUserId()
    }).then(res => {
      form.value.id = res.data
    })
  })
}

const init = () => {
  getNoPublic()
}

init()

let time = null;

const delUpdateVideo = () => {
  clearTimeout(timeUp)

  stopUploadVideo(subFileHash.value, form.value.updateBy).then(res => {
    if (res.code === 200) {
      bMessage("停止上传成功", "success")
      init()
      diaStatusStop.value = false
      prop.value = 0
    }

  })
}

const delFile = () => {
  delPostImg(form.value.id, subFile.value, form.value.updateBy).then(res => {
    if (res.code === 200) {
      init()
      diaStatusDel.value = false
    }
  })
}

const okLong = (id) => {
  subFile.value = id
  time = setTimeout(() => {
    diaStatusDel.value = true
  }, 500)
}

const noLong = () => {
  clearTimeout(time)
}


</script>

<template>
  <!--删除文件-->
  <dialogue title="系统" content="是否删除这个文件？" v-model="diaStatusDel" :def_button="false">
    <view class="button">
      <button @click="delFile" >删除</button>
      <button @click="diaStatusDel = !diaStatusDel" >不删除</button>
    </view>
  </dialogue>

  <!--删除上传中的-->
  <dialogue title="系统" content="是否停止上传？" v-model="diaStatusStop"  :def_button="false">
    <view class="button">
      <button @click="delUpdateVideo">停止</button>
      <button @click="diaStatusStop = !diaStatusStop">不停止</button>
    </view>
  </dialogue>

  <!--退出-->
  <dialogue title="退出" content="保留这次编辑？"  :def_button="false" v-model="diaStatus">
    <view class="button">
      <button @click="noSave">不保留</button>
      <button @click="save">保留</button>
    </view>
  </dialogue>

  <view class="back">
    <v-toolbar height="50" >
      <v-btn icon="mdi-arrow-left" @click="exit"></v-btn>
      <v-toolbar-title></v-toolbar-title>
      <v-btn @click="submit">发布</v-btn>
    </v-toolbar>

    <v-container>

      <view class="form">

        <view class="text">
          <textarea maxlength="-1" v-model="form.content" :auto-height="true"  placeholder="分享一下你此刻的想法.."></textarea>
        </view>

        <view class="img">
          <v-row>
            <v-col
                v-for="n in file"
                :key="n"
                :cols="4"
            >
              <v-img
                  aspect-ratio="1"
                  cover
                  v-if="n.type === 'png' || n.type === 'jpg' || n.type === 'jpeg' || n.type === 'gif' || n.type === 'bmp' || n.type === 'webp'"
                  :src="baseUrl + n.clientUrl"
                  @click="previewImage(baseUrl + n.clientUrl)"
              >
                <template v-slot:placeholder>
                  <v-row
                      align="center"
                      class="fill-height ma-0"
                      justify="center"
                  >
                    <v-progress-circular
                        color="grey-lighten-5"
                        indeterminate
                    ></v-progress-circular>
                  </v-row>
                </template>
              </v-img>
              <video
                  class="edit_post_video"
                  v-if="n.type === 'm4v' || n.type === 'mp4' "
                  :src="baseUrl + n.clientUrl"
                  object-fit="cover"
                  @touchstart="okLong(n.id)"
                  @touchend="noLong"
              ></video>

            </v-col>
            <v-col :cols="4" v-if="prop === 0 && file.length === 0">
              <view class="add" @click="updateImg()">
                <text>+</text>
              </view>
            </v-col>
            <v-col :cols="4" v-if="prop === 0 && file.length === 0">
              <view class="add" >
                <uni-icons class="icon" @click="fn()" type="videocam" size="30"></uni-icons>
              </view>
            </v-col>
            <v-col :cols="4">
              <view class="progress">
                <v-badge v-if="prop !== 0" @click="diaStatusStop = !diaStatusDel" content="删除" color="error" text-color="white">
                  <v-progress-circular
                      :model-value="prop"
                      height="10"
                      width="10"
                      :rotate="360"
                      :size="100"
                      color="#f66f0e"
                  >
                    <template v-slot:default> {{ prop }} % </template>
                  </v-progress-circular>
                </v-badge>
              </view>
            </v-col>
          </v-row>
        </view>


      </view>

    </v-container>
  </view>
</template>

<style scoped lang="scss">
@use "../../static/css/main.scss";
.btn{
  .icon{
    margin-left: 20px;
  }
  padding: 12px;
}
.button{
  button::after{
    border: none;
  }
  button{
    width: 80%;
    margin: 0 10px;
    background: white;
  }
  display: flex;
}
.back{
  @include main.useTheme(){
    .form {

      .progress {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 110px;
      }

      .btn{
        margin-top: 10px;
      }
      .text {
        textarea {
          width: 100%;
          border-radius: 5px;
          font-size: 16px;
        }
        padding-bottom: 10vh;
      }
      .add {
        height: 110px;
        display: flex;
        justify-content: center;
        font-size: 10vw;
        align-items: center;
        color: main.getVal("primary_border_color");
        border: 1px solid main.getVal("primary_border_color");
        border-radius: 5px;
      }
    }


  }
}

</style>